package display.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import common.Common;

import prefuse.data.Table;
import prefuse.data.Tuple;
import prefuse.data.io.CSVTableReader;
import prefuse.data.io.DataIOException;
import prefuse.data.parser.DataParser;
import prefuse.data.parser.DoubleParser;
import prefuse.data.parser.ParserFactory;
import prefuse.data.parser.StringParser;

import data.process.CurveGen;
import display.structure.Belt;
import display.structure.Wheel;

public class StockWheelAnimator extends WheelSpeedAnimator{
	private Belt belt = null;
	public StockWheelAnimator(String group, Wheel wheel, Belt belt) {
		super(group, 1, wheel);
		this.belt = belt;
		String file = Common.stockFolder(wheel.companyName)+wheel.companyName+".csv";
		if (! new File(file).exists()) {
			throw new IllegalStateException("cannot find the stock file");
		}
		try {
			stockTable = new CSVTableReader(
					new ParserFactory(new DataParser[]{new DoubleParser(),new StringParser()
					})).readTable(file);
			stockTable.addColumn("date", int.class);
			for(Iterator<Tuple> it = stockTable.tuples(); it.hasNext(); ){
				Tuple tuple = it.next();
				tuple.setInt("date", Integer.parseInt(tuple.getString("Date").replace("-", "")));
			}
			CurveGen.smooth(stockTable, new double[]{0.2,0.2,0.2,0.2,0.2},"Close");
			List<Double> array = new ArrayList<Double>();
			array.add(0.0);
			for(int i = 1; i<stockTable.getTupleCount(); i++){
				array.add(stockTable.getDouble(i, "Close")-stockTable.getDouble(i-1, "Close"));
//				System.out.println(array.get(array.size()-1));
			}
			for(int i = 0; i<stockTable.getTupleCount(); i++){
				stockTable.setDouble(i, "Close", array.get(i));
			}
			minAbsStock = Double.MAX_VALUE;
			maxAbsStock = 0;
			for(Iterator<Tuple> it = stockTable.tuples(); it.hasNext();){
				Tuple tuple = it.next();
				double close = tuple.getDouble("Close");
				if (maxAbsStock < Math.abs(close)) {
					maxAbsStock = Math.abs(close);
				}
				if (minAbsStock > Math.abs(close)) {
					minAbsStock = Math.abs(close);
				}
//				System.out.println(tuple.getDouble("Close"));
			}
			System.out.println(""+minAbsStock+": minStock");
			System.out.println(""+maxAbsStock+": maxStock");
		} catch (DataIOException e) {
			e.printStackTrace();
		}
	}
	private double minAbsStock = 0;
	private double maxAbsStock = 0;
	private Table stockTable = null;
	private double maxSpeed = 2;
	@Override
	public void run(double frac) {
		//clockwise is stock price going down
		prefuse.data.util.Index index = stockTable.index("date");
		int row = index.get(belt.maxDate);
		if (row > 0) {
			Tuple stockTuple = stockTable.getTuple(row);
			double value = stockTuple.getDouble("Close");
			double speed = maxSpeed * value/maxAbsStock;
			setRadPerSec(0-speed);
		}
		super.run(frac);
		wheel.updateStarLayers();
	}
}
